<template>
    <view>
        <!-- pages/cart/index.wxml -->
        <!-- 头部 -->
        <navber id="head-navber" :navbarData="navbarData"></navber>
        <view class="emptyCart" v-if="cartList.length == 0">
            <image src="/static/assets/imgs/navbar/nodata_cart.png"></image>
            <view class="emptyTip">购物车暂无商品~</view>
            <view class="seeGoods" @tap="toCategory">去逛逛</view>
        </view>
        <!-- 按钮编辑 -->
        <view class="cart-but" v-if="cartList.length != 0">
            <view class="cart-but-allImg" @tap="onAllSelect">
                <image :src="imgUrl + '/imgs/cart/' + (is_all ? '' : 'not_') + 'select.png'"></image>
            </view>
            <view class="cart-but-all" @tap="onAllSelect">全选</view>
            <view :class="'cart-but-edit ' + (is_edit == '完成' ? 'cart-but-complete' : '')" @tap="goods_edit($event, { type: is_edit })" :data-type="is_edit">
                {{ is_edit }}
            </view>
        </view>
        <!-- 商品 -->
        <view class="cart-goods" v-if="cartList.length != 0" :style="isIphonex ? 'margin-top: 100rpx;' : ''">
            <view class="" v-for="(item, index) in cartList" :key="index">
                <view class="cart-store">
                    <view class="cart-store-line">
                        <view class="cart-goods-store-selected" @tap="onItemSelectStore($event, { index })" :data-index="index">
                            <image :src="imgUrl + '/imgs/cart/' + (item.selected ? '' : 'not_') + 'select.png'"></image>
                        </view>
                        <view class="cart-store-name">{{ item.store['store_name'] }}</view>
                    </view>
                    <view class="cart-goods-item" v-for="(itemx, indexx) in item.list" :key="itemx.indexx">
                        <view class="cart-goods-item-selected" @tap="onItemSelect($event, { index, indexx })" :data-index="index" :data-indexx="indexx">
                            <image :src="imgUrl + '/imgs/cart/' + (itemx.selected ? '' : 'not_') + 'select.png'"></image>
                        </view>

                        <view class="cart-goods-item-info">
                            <view class="cart-goods-item-info-img" @tap="goodsDetail($event, { goods_id: itemx.goods_id })" :data-goods_id="itemx.goods_id">
                                <image mode="aspectFill" :src="itemx.goods_image + '?x-oss-process=image/resize,w_120'"></image>
                            </view>
                            <view class="cart-goods-item-info-text">
                                <view class="cart-goods-item-info-text-title" @tap="goodsDetail($event, { goods_id: itemx.goods_id })" :data-goods_id="itemx.goods_id">
                                    {{ itemx.goods_title }}
                                </view>
                                <view class="cart-goods-item-info-text-title-attr">
                                    {{ itemx.attribute_names }}
                                </view>
                                <view class="cart-goods-item-info-text-pn">
                                    <view class="cart-goods-item-info-text-pn-price">
                                        <view class="cart-goods-item-info-text-pn-price1">￥</view>
                                        <view class="cart-goods-item-info-text-pn-price2">{{ itemx.goods_sell_price }}</view>
                                    </view>
                                    <van-stepper
                                        input-class="goods-number-input"
                                        :value="itemx.goods_number"
                                        min="0"
                                        :max="itemx.goods_storage"
                                        @change="onNumChange($event, { index, indexx })"
                                        :data-index="index"
                                        :data-indexx="indexx"
                                    />
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="cart-store-lose-tip" v-if="cartLoseList.length > 0">- 失效商品 -</view>
            <view class="" v-for="(item, index) in cartLoseList" :key="index">
                <view class="cart-store">
                    <view class="cart-store-line">
                        <view class="cart-goods-store-selected" @tap="onItemSelectStoreLose($event, { index })" :data-index="index">
                            <image :src="imgUrl + '/imgs/cart/' + (item.selected ? '' : 'not_') + 'select.png'"></image>
                        </view>
                        <view class="cart-store-name">{{ item.store['store_name'] }}</view>
                    </view>
                    <view class="cart-goods-item" v-for="(itemx, indexx) in item.list" :key="itemx.indexx">
                        <view class="cart-goods-item-selected" @tap="onItemSelectLose($event, { index, indexx })" :data-index="index" :data-indexx="indexx">
                            <image :src="imgUrl + '/imgs/cart/' + (itemx.selected ? '' : 'not_') + 'select.png'"></image>
                        </view>

                        <view class="cart-goods-item-info">
                            <view class="cart-goods-item-info-img" @tap="goodsDetail($event, { goods_id: itemx.goods_id })" :data-goods_id="itemx.goods_id">
                                <image mode="aspectFill" :src="itemx.goods_image + '?x-oss-process=image/resize,w_120'"></image>
                            </view>
                            <view class="cart-goods-item-info-text">
                                <view class="cart-goods-item-info-text-title" @tap="goodsDetail($event, { goods_id: itemx.goods_id })" :data-goods_id="itemx.goods_id">
                                    {{ itemx.goods_title }}
                                </view>
                                <view class="cart-goods-item-info-text-title-attr">
                                    {{ itemx.attribute_names }}
                                </view>
                                <view class="cart-goods-item-info-text-pn">
                                    <view class="cart-goods-item-info-text-pn-price">
                                        <view class="cart-goods-item-info-text-pn-price1">￥</view>
                                        <view class="cart-goods-item-info-text-pn-price2">{{ itemx.goods_sell_price }}</view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view style="width: 100%; height: 180px"></view>
        </view>

        <!-- 结算 -->
        <view class="cart-order" v-if="cartList.length != 0">
            <view class="cart-order-disc" v-if="false">
                <view class="cart-order-disc-text">优惠：</view>
                <view class="cart-order-disc-price">￥{{ dis_price }}</view>
            </view>
            <view class="cart-order-price">
                <view class="cart-order-price-tag">当前价格不包含运费</view>
                <view class="cart-order-price-view">
                    <view class="cart-order-price-text">总价：</view>
                    <view class="cart-order-price-price">¥{{ count_price }}</view>
                </view>
            </view>
            <view class="cart-order-submit" v-if="is_edit == '编辑'" @tap="onSubmit">提交订单</view>
            <view class="cart-del-submit" v-if="is_edit == '完成'" @tap="delMoreCart">删除</view>
        </view>
    </view>
</template>

<script>
import navber from '@/components/navber/index';
import numinput from '@/components/numinput/index';
// pages/cart/index.js
const Config = require('../../config/index.js');

const Api = require('../../api/index.js');

const app = getApp();
export default {
    components: {
        navber,
        numinput
    },
    data() {
        return {
            navbarData: {
                title: '购物车' //顶部标题
            },
            //导航栏
            imgUrl: Config.imgUrl,
            //图片url
            is_edit: '编辑',
            //是否编辑
            is_editb: true,
            //是否是编辑状态
            is_all: false,
            // but_scorll:false,
            cartList: [],
            cartLoseList: [],
            count_price: 0,
            //总价
            dis_price: 0,
            //优惠
            isIphonex: app.globalData.isIphoneX,
            member_level: 0,
            public_type: 0,
            //是否参与公益 1本次愿意，2愿意以后不提醒，3本次忽略，4不愿意以后不提醒
            show: false //公益弹窗
        };
    },
    onShow() {
        this.getData();
        this.setData({
            is_all: false,
            member_level: app.globalData.userInfo.member_level // member_level:0
        }); // let that = this;
        // setTimeout(function(){
        // },1500);
    },
    onPullDownRefresh: function () {
        this.getData();
        uni.stopPullDownRefresh(); // setTimeout(function(){
        //   wx.stopPullDownRefresh();
        // },4000);
    },
    methods: {
        goods_edit(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //编辑
            var type = e.currentTarget.dataset.type == '编辑' ? '完成' : '编辑';
            var is_edit_b = true;

            if (type != '编辑') {
                is_edit_b = false;
            }

            this.setData({
                is_edit: type,
                is_editb: is_edit_b
            });
        },

        onNumChange(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            let goods_number = e.detail;
            var index = parseInt(e.currentTarget.dataset.index);
            var indexx = parseInt(e.currentTarget.dataset.indexx);
            var data = this.cartList;
            data[index].list[indexx].goods_number = goods_number;
            this.setData({
                cartList: data
            });
            this.editCart(index, indexx);
            this.statistics_price();
        },

        delMoreCart(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            var cart_id = '';
            var data = this.cartList;

            for (var i = 0; i < data.length; i++) {
                var list = data[i].list;

                for (var j = 0; j < list.length; j++) {
                    if (list[j].selected == true) {
                        if (cart_id == '') {
                            cart_id += list[j].id;
                        } else {
                            cart_id += ',' + list[j].id;
                        }
                    }
                }
            }

            var data = this.cartLoseList;

            for (var i = 0; i < data.length; i++) {
                var list = data[i].list;

                for (var j = 0; j < list.length; j++) {
                    if (list[j].selected == true) {
                        if (cart_id == '') {
                            cart_id += list[j].id;
                        } else {
                            cart_id += ',' + list[j].id;
                        }
                    }
                }
            }

            if (cart_id == '') {
                return uni.showToast({
                    title: '请选择商品',
                    icon: 'none',
                    duration: 2000
                });
            }

            var json = {
                id: cart_id
            };
            Api.goodsCartDelete(json).then((res) => {
                if (res.code == 1) {
                    this.getData();
                }
            }); // console.log(cart_id);
        },

        onAllSelectIn() {
            //全选
            var data = this.cartList;

            for (var i = 0; i < data.length; i++) {
                data[i].selected = true;

                for (var j = 0; j < data[i].list.length; j++) {
                    data[i].list[j].selected = true;
                }
            }

            this.setData({
                cartList: data,
                is_all: true
            });
        },

        onAllSelect(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //全选
            var data = this.cartList;

            for (var i = 0; i < data.length; i++) {
                if (this.is_all) {
                    data[i].selected = false;
                } else {
                    data[i].selected = true;
                }

                for (var j = 0; j < data[i].list.length; j++) {
                    if (this.is_all) {
                        data[i].list[j].selected = false;
                    } else {
                        data[i].list[j].selected = true;
                    }
                }
            }

            this.setData({
                cartList: data,
                is_all: !this.is_all
            }); // this.statistics_price();
        },

        onItemSelectStore(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            var index = e.currentTarget.dataset.index;
            var data = this.cartList;
            data[index].selected = !data[index].selected;
            var is_all = true;

            for (var i = 0; i < data.length; i++) {
                if (data[i].selected == false) {
                    is_all = false;
                }
            }

            var list = data[index].list;

            for (var i = 0; i < list.length; i++) {
                list[i].selected = data[index].selected;
            }

            data[index].list = list;
            this.setData({
                cartList: data,
                is_all: is_all
            });
            this.statistics_price();
        },

        onItemSelect(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //单选
            var index = e.currentTarget.dataset.index;
            var indexx = e.currentTarget.dataset.indexx;
            var data = this.cartList;
            var is_all = true;
            data[index].list[indexx].selected = !data[index].list[indexx].selected;

            for (var i = 0; i < data.length; i++) {
                var is_selected = true;
                var list = data[i].list;

                for (var j = 0; j < list.length; j++) {
                    if (list[j].selected == false) {
                        is_selected = false;
                    }
                }

                data[i].selected = is_selected;

                if (is_selected == false) {
                    is_all = false;
                }
            }

            this.setData({
                cartList: data,
                is_all: is_all
            });
            this.statistics_price();
        },

        onItemSelectStoreLose(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            var index = e.currentTarget.dataset.index;
            var data = this.cartLoseList;
            data[index].selected = !data[index].selected;
            var is_all = true;

            for (var i = 0; i < data.length; i++) {
                if (data[i].selected == false) {
                    is_all = false;
                }
            }

            var list = data[index].list;

            for (var i = 0; i < list.length; i++) {
                list[i].selected = data[index].selected;
            }

            data[index].list = list;
            this.setData({
                cartLoseList: data
            });
        },

        onItemSelectLose(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            //单选
            var index = e.currentTarget.dataset.index;
            var indexx = e.currentTarget.dataset.indexx;
            var data = this.cartLoseList;
            var is_all = true;
            data[index].list[indexx].selected = !data[index].list[indexx].selected;

            for (var i = 0; i < data.length; i++) {
                var is_selected = true;
                var list = data[i].list;

                for (var j = 0; j < list.length; j++) {
                    if (list[j].selected == false) {
                        is_selected = false;
                    }
                }

                data[i].selected = is_selected;

                if (is_selected == false) {
                    is_all = false;
                }
            }

            this.setData({
                cartLoseList: data
            });
        },

        open_vip() {
            //开通vip
            uni.navigateTo({
                url: '/pages/user/vip/index'
            });
        },

        statistics_price() {
            //统计金额
            var data = this.cartList;
            var count_price = 0;
            var dis_price = 0;

            for (var i = 0; i < data.length; i++) {
                var list = data[i].list;

                for (var j = 0; j < list.length; j++) {
                    if (list[j].selected == true) {
                        count_price += parseFloat(list[j].goods_sell_price) * list[j].goods_number;
                        dis_price += parseFloat(list[j].goods_market_price) * list[j].goods_number - parseFloat(list[j].goods_sell_price) * list[j].goods_number;
                    }
                }
            }

            this.setData({
                count_price: count_price.toFixed(2),
                dis_price: dis_price.toFixed(2)
            });
        },

        onSubmit(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            this.submit_order(); // var public_type = parseInt(this.data.public_type);
            // if (public_type == 0 || public_type == 1 || public_type == 3) {
            //   this.show_public();
            // } else {
            //   this.submit_order();
            // }
        },

        submit_order() {
            //提交订单
            var data = this.cartList;
            var goods_list = [];

            for (var i = 0; i < data.length; i++) {
                var list = data[i].list;

                for (var j = 0; j < list.length; j++) {
                    if (list[j].selected == true) {
                        goods_list.push({
                            goods_id: list[j].goods_id,
                            attribute_ids: list[j].attribute_ids,
                            goods_number: list[j].goods_number
                        });
                    }
                }
            }

            if (goods_list.length == 0) {
                return uni.showToast({
                    title: '请选择商品',
                    icon: 'none',
                    duration: 2000
                });
            }

            var goods_list_json = JSON.stringify(goods_list); // console.log(goods_list_json);

            uni.navigateTo({
                url: '/pages/goodsDetail/order/index?type=goods_order&goods_info=' + goods_list_json
            });
        },

        toCategory(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            uni.switchTab({
                url: '/pages/index/index'
            });
        },

        getData(e) {
            //获取数据
            Api.goodsMyCart().then((res) => {
                var data = res.data; // var public_type = parseInt(data['public_type']) == 0 ? 0 : parseInt(data['public_type']);

                var cat_sum = data.cat_sum;
                this.setData({
                    cartList: data.cart_list,
                    cartLoseList: data.cart_lose_list // public_type: public_type
                });
                this.onAllSelectIn();
                this.statistics_price();

                if (cat_sum == 0) {
                    uni.removeTabBarBadge({
                        index: app.globalData.catIndex
                    });
                } else {
                    uni.setTabBarBadge({
                        index: app.globalData.catIndex,
                        text: cat_sum + ''
                    });
                }
            });
        },

        editCart(index, indexx) {
            //修改数据
            let that = this;
            var json = {
                id: this.cartList[index].list[indexx].id,
                goods_number: this.cartList[index].list[indexx].goods_number
            };
            Api.goodsCartEdit(json).then((res) => {
                if (res.code != 1) {
                    uni.showToast({
                        title: '操作失败'
                    });
                }

                that.getData();
            });
        },

        //开启公益弹窗
        show_public() {
            this.setData({
                show: true
            });
        },

        onClosePublic() {
            this.setData({
                show: false
            });
        },

        onSubmitPublic() {
            this.setData({
                show: false
            });
            this.submit_order();
        },

        setPublicType() {
            var json = {
                public_type: this.public_type
            }; //设置公益状态

            Api.userPublicType(json).then((res) => {
                if (res.code != 1) {
                    uni.showToast({
                        title: '操作失败'
                    });
                }
            });
            this.onSubmitPublic();
        },

        //公益弹窗选择
        public_select(e) {
            var id = e.currentTarget.dataset.id;
            this.setData({
                public_type: id
            });
        },

        goodsDetail(e, _dataset) {
            
            if (!e.currentTarget) {
                if (_dataSet.tagId) {
                    e.currentTarget = {
                        id: _dataSet.tagId
                    };
                } else {
                    e.currentTarget = {
                        dataset: _dataSet
                    };
                }
            }
            
            // 商品详情
            uni.navigateTo({
                url: '/pages/goodsDetail/index?id=' + e.currentTarget.dataset.goods_id
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
